package org.example.controller;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.example.dto.Dog;
import org.example.service.DynamicsSwitchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.List;

@RestController
@RequestMapping("/dy3")
public class AddDynamicDataSource {

    @Resource
    DynamicRoutingDataSource dataSource;

    @Autowired
    private DynamicsSwitchService ds;

    /**
     * 动态添加数据源
     * */
    @RequestMapping("/add")
    public List<Dog> list(HttpServletRequest request){

        DataSource d = DataSourceBuilder
                .create()
                .url("jdbc:mysql://localhost:3306/sss")
                .password("1234")
                .username("root")
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .build();

        dataSource.addDataSource("hh", d);

        // 注意，这里存入session的key要和Service方法中@DS注解中的值对应上。而value就是数据源的名字
        request.getSession().setAttribute("dataSourceKey", "hh");

        return ds.findList();
    }
}
